import 'dart:io';
import 'dart:convert';
import 'package:get/get.dart';
import '../models/index.dart';
import 'share_page_generator_service.dart';
import 'dart:developer' as developer;

/// 🌐 本地分享页面HTTP服务器
/// 
/// 提供分享页面的HTTP服务，供微信分享链接访问
/// 注意：在生产环境中应该使用专门的后端服务器
class LocalShareServerService extends GetxService {
  HttpServer? _server;
  static const int _defaultPort = 8080;
  static const String _defaultHost = '0.0.0.0';
  
  /// 服务器运行状态
  final RxBool _isRunning = false.obs;
  bool get isRunning => _isRunning.value;
  
  /// 服务器端口
  final RxInt _port = _defaultPort.obs;
  int get port => _port.value;
  
  /// 服务器地址
  final RxString _host = _defaultHost.obs;
  String get host => _host.value;
  
  /// 存储活动数据的缓存
  final Map<String, ActivityModel> _activityCache = {};
  
  /// 存储生成的HTML页面缓存
  final Map<String, String> _pageCache = {};

  @override
  Future<void> onInit() async {
    super.onInit();
    // 服务初始化时不自动启动服务器
    // 可以根据需要手动启动
  }

  @override
  void onClose() {
    stopServer();
    super.onClose();
  }

  /// 启动HTTP服务器
  Future<bool> startServer({int? customPort}) async {
    if (_isRunning.value) {
      developer.log('⚠️ HTTP服务器已在运行中');
      return true;
    }

    try {
      final serverPort = customPort ?? _defaultPort;
      
      developer.log('🚀 正在启动本地分享页面服务器...');
      developer.log('📡 端口: $serverPort');
      
      _server = await HttpServer.bind(_defaultHost, serverPort);
      _port.value = serverPort;
      _isRunning.value = true;
      
      // 监听请求
      _server!.listen(_handleRequest);
      
      developer.log('✅ 本地分享页面服务器启动成功');
      developer.log('🌐 服务器地址: http://$_defaultHost:$serverPort');
      developer.log('📱 分享链接格式: http://$_defaultHost:$serverPort/share/activity/{activityId}');
      
      return true;
      
    } catch (e) {
      developer.log('❌ 启动服务器失败: $e');
      _isRunning.value = false;
      return false;
    }
  }

  /// 停止HTTP服务器
  Future<void> stopServer() async {
    if (_server != null) {
      try {
        await _server!.close();
        developer.log('🛑 本地分享页面服务器已停止');
      } catch (e) {
        developer.log('❌ 停止服务器失败: $e');
      }
      
      _server = null;
      _isRunning.value = false;
    }
  }

  /// 处理HTTP请求
  Future<void> _handleRequest(HttpRequest request) async {
    try {
      final uri = request.uri;
      developer.log('📥 收到请求: ${request.method} ${uri.path}');
      
      // 设置CORS头部，允许跨域访问
      request.response.headers.set('Access-Control-Allow-Origin', '*');
      request.response.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
      request.response.headers.set('Access-Control-Allow-Headers', 'Origin, Content-Type');
      
      if (request.method == 'OPTIONS') {
        // 处理预检请求
        request.response.statusCode = HttpStatus.ok;
        await request.response.close();
        return;
      }
      
      // 路由处理
      if (uri.path.startsWith('/share/activity/')) {
        await _handleActivityShareRequest(request);
      } else if (uri.path == '/health') {
        await _handleHealthCheck(request);
      } else if (uri.path == '/api/stats/download-click') {
        await _handleDownloadStats(request);
      } else if (uri.path == '/api/stats/page-view') {
        await _handlePageViewStats(request);
      } else {
        await _handle404(request);
      }
      
    } catch (e) {
      developer.log('❌ 处理请求失败: $e');
      await _handleError(request, e);
    }
  }

  /// 处理活动分享页面请求
  Future<void> _handleActivityShareRequest(HttpRequest request) async {
    try {
      final uri = request.uri;
      final pathSegments = uri.pathSegments;
      
      if (pathSegments.length >= 3 && pathSegments[0] == 'share' && pathSegments[1] == 'activity') {
        final activityId = pathSegments[2];
        
        // 从缓存中获取活动数据
        final activity = _activityCache[activityId];
        if (activity == null) {
          await _handleActivityNotFound(request, activityId);
          return;
        }
        
        // 检查页面缓存
        final cacheKey = 'activity_$activityId';
        String? htmlContent = _pageCache[cacheKey];
        
        if (htmlContent == null) {
          // 生成分享页面
          final shareUrl = 'http://$host:$port${uri.path}';
          htmlContent = await SharePageGeneratorService.generateActivitySharePage(
            activity: activity,
            shareUrl: shareUrl,
          );
          
          // 缓存页面内容
          _pageCache[cacheKey] = htmlContent;
        }
        
        // 返回HTML页面
        request.response.headers.contentType = ContentType.html;
        request.response.write(htmlContent);
        await request.response.close();
        
        developer.log('✅ 成功返回活动分享页面: $activityId');
        
      } else {
        await _handle404(request);
      }
      
    } catch (e) {
      developer.log('❌ 处理活动分享页面请求失败: $e');
      await _handleError(request, e);
    }
  }

  /// 处理健康检查请求
  Future<void> _handleHealthCheck(HttpRequest request) async {
    final healthInfo = {
      'status': 'ok',
      'server': 'playtrue3-share-server',
      'version': '1.0.0',
      'timestamp': DateTime.now().toIso8601String(),
      'port': _port.value,
      'cached_activities': _activityCache.length,
      'cached_pages': _pageCache.length,
    };
    
    request.response.headers.contentType = ContentType.json;
    request.response.write(jsonEncode(healthInfo));
    await request.response.close();
  }

  /// 处理下载统计请求
  Future<void> _handleDownloadStats(HttpRequest request) async {
    if (request.method == 'POST') {
      try {
        final body = await utf8.decoder.bind(request).join();
        final data = jsonDecode(body);
        
        developer.log('📊 下载点击统计: $data');
        
        // 这里可以将统计数据发送到真实的统计服务
        // 或者存储到本地数据库
        
        request.response.headers.contentType = ContentType.json;
        request.response.write(jsonEncode({'status': 'success'}));
        await request.response.close();
        
      } catch (e) {
        await _handleError(request, e);
      }
    } else {
      request.response.statusCode = HttpStatus.methodNotAllowed;
      await request.response.close();
    }
  }

  /// 处理页面访问统计请求
  Future<void> _handlePageViewStats(HttpRequest request) async {
    if (request.method == 'POST') {
      try {
        final body = await utf8.decoder.bind(request).join();
        final data = jsonDecode(body);
        
        developer.log('📊 页面访问统计: $data');
        
        request.response.headers.contentType = ContentType.json;
        request.response.write(jsonEncode({'status': 'success'}));
        await request.response.close();
        
      } catch (e) {
        await _handleError(request, e);
      }
    } else {
      request.response.statusCode = HttpStatus.methodNotAllowed;
      await request.response.close();
    }
  }

  /// 处理404错误
  Future<void> _handle404(HttpRequest request) async {
    request.response.statusCode = HttpStatus.notFound;
    request.response.headers.contentType = ContentType.html;
    request.response.write('''
<!DOCTYPE html>
<html>
<head>
    <title>页面未找到 - 玩真的</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            margin: 0; padding: 20px; min-height: 100vh;
            display: flex; align-items: center; justify-content: center;
        }
        .container {
            max-width: 400px; background: white; border-radius: 15px;
            padding: 30px; text-align: center;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        .title { font-size: 24px; margin-bottom: 15px; color: #333; }
        .message { font-size: 16px; color: #666; margin-bottom: 20px; }
        .btn {
            display: inline-block; background: #4CAF50; color: white;
            padding: 10px 20px; border-radius: 5px; text-decoration: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="title">😅 页面未找到</div>
        <div class="message">抱歉，您访问的页面不存在</div>
        <a href="#" class="btn" onclick="downloadApp()">下载玩真的APP</a>
    </div>
    <script>
        function downloadApp() {
            const userAgent = navigator.userAgent.toLowerCase();
            if (/android/i.test(userAgent)) {
                window.location.href = 'https://play.google.com/store/apps/details?id=com.playtruly.wanzhende2025';
            } else if (/iphone|ipad|ipod/i.test(userAgent)) {
                window.location.href = 'https://apps.apple.com/cn/app/id[YOUR_APP_ID]';
            } else {
                window.location.href = 'https://app.playtruly.cn/download';
            }
        }
    </script>
</body>
</html>
    ''');
    await request.response.close();
  }

  /// 处理活动未找到错误
  Future<void> _handleActivityNotFound(HttpRequest request, String activityId) async {
    request.response.statusCode = HttpStatus.notFound;
    request.response.headers.contentType = ContentType.html;
    request.response.write('''
<!DOCTYPE html>
<html>
<head>
    <title>活动未找到 - 玩真的</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            margin: 0; padding: 20px; min-height: 100vh;
            display: flex; align-items: center; justify-content: center;
        }
        .container {
            max-width: 400px; background: white; border-radius: 15px;
            padding: 30px; text-align: center;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        .title { font-size: 24px; margin-bottom: 15px; color: #333; }
        .message { font-size: 16px; color: #666; margin-bottom: 20px; }
        .btn {
            display: inline-block; background: #4CAF50; color: white;
            padding: 10px 20px; border-radius: 5px; text-decoration: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="title">🔍 活动未找到</div>
        <div class="message">活动可能已结束或不存在<br>活动ID: $activityId</div>
        <a href="#" class="btn" onclick="downloadApp()">下载玩真的APP</a>
    </div>
    <script>
        function downloadApp() {
            const userAgent = navigator.userAgent.toLowerCase();
            if (/android/i.test(userAgent)) {
                window.location.href = 'https://play.google.com/store/apps/details?id=com.playtruly.wanzhende2025';
            } else if (/iphone|ipad|ipod/i.test(userAgent)) {
                window.location.href = 'https://apps.apple.com/cn/app/id[YOUR_APP_ID]';
            } else {
                window.location.href = 'https://app.playtruly.cn/download';
            }
        }
    </script>
</body>
</html>
    ''');
    await request.response.close();
  }

  /// 处理服务器错误
  Future<void> _handleError(HttpRequest request, dynamic error) async {
    request.response.statusCode = HttpStatus.internalServerError;
    request.response.headers.contentType = ContentType.json;
    request.response.write(jsonEncode({
      'error': 'Internal Server Error',
      'message': error.toString(),
      'timestamp': DateTime.now().toIso8601String(),
    }));
    await request.response.close();
  }

  /// 注册活动数据到缓存
  void registerActivity(ActivityModel activity) {
    _activityCache[activity.id] = activity;
    
    // 清除对应的页面缓存，以便重新生成
    _pageCache.remove('activity_${activity.id}');
    
    developer.log('📝 活动已注册到分享服务器: ${activity.id} - ${activity.title}');
  }

  /// 批量注册活动数据
  void registerActivities(List<ActivityModel> activities) {
    for (final activity in activities) {
      registerActivity(activity);
    }
    developer.log('📝 批量注册了 ${activities.length} 个活动到分享服务器');
  }

  /// 移除活动数据
  void removeActivity(String activityId) {
    _activityCache.remove(activityId);
    _pageCache.remove('activity_$activityId');
    developer.log('🗑️ 已从分享服务器移除活动: $activityId');
  }

  /// 清空所有缓存
  void clearCache() {
    _activityCache.clear();
    _pageCache.clear();
    developer.log('🧹 已清空分享服务器缓存');
  }

  /// 获取服务器统计信息
  Map<String, dynamic> getServerStats() {
    return {
      'isRunning': _isRunning.value,
      'host': _host.value,
      'port': _port.value,
      'cachedActivities': _activityCache.length,
      'cachedPages': _pageCache.length,
      'serverUrl': 'http://${_host.value}:${_port.value}',
    };
  }

  /// 生成活动分享URL
  String generateActivityShareUrl(String activityId) {
    return 'http://${_host.value}:${_port.value}/share/activity/$activityId';
  }
}
